//
//  QQApiShareEntryControllerViewController.m
//  sdkDemo
//
//  Created by JeaminW on 13-7-28.
//  Copyright (c) 2013年 xiaolongzhang. All rights reserved.
//

#if ! __has_feature(objc_arc)
#error This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC).
#endif

#import "QQAPIShareEntry.h"
#import "QuickDialogController.h"
#import "QRootElement.h"
#import "QBooleanElement.h"
#import <objc/runtime.h>

#import "sdkDemoAppDelegate.h"
#import "SDKCall.h"
#import "NSData+HexAdditions.h"

typedef void (^verifyResultBlock)(NSURLResponse *response, NSDictionary *result);

#if BUILD_QQAPIDEMO
#import "TencentOpenAPI/QQApiInterface.h"
#endif
#if !QQ_OPEN_SDK_LITE
#import "TencentOpenAPI/QQApiInterface+Full.h"
#import "TencentOpenAPI/QQApiInterfaceObject+Full.h"
#endif

#import <TencentOpenAPI/QQApiInterfaceObject.h>

#define SDK_TEST_IMAGE_FILE_NAME             @"/test"  //为了测试多种图片类型的分享流程，这里需要在应用目录下放置不同类型图片

@implementation QQApiShareEntry

+ (UIViewController *)EntryController
{
#if QQ_OPEN_SDK_LITE
    UIViewController *QDialog = [QuickDialogController controllerForRoot:[QRootElement rootForJSON:@"QQAPIDemo_lite" withObject:nil]];
#else
    UIViewController *QDialog = [QuickDialogController controllerForRoot:[QRootElement rootForJSON:@"QQAPIDemo" withObject:nil]];
#endif
    return QDialog;
}

+ (UIViewController *)QQqunEntryController {
    UIViewController *QDialog = [QuickDialogController controllerForRoot:[QRootElement rootForJSON:@"QQAPIQQqunDemo" withObject:nil]];
    return QDialog;
}

+ (BOOL)isRequestFromQQ {
    id<UIApplicationDelegate> appDelegate = [[UIApplication sharedApplication] delegate];
    if ([appDelegate isKindOfClass:sdkDemoAppDelegate.class]) {
        return ((sdkDemoAppDelegate*)appDelegate).isRequestFromQQ;
    }
    return NO;
}

#if BUILD_QQAPIDEMO
#pragma mark - QQApiInterfaceDelegate
+ (void)onReq:(QQBaseReq *)req
{
    switch (req.type)
    {
        case EGETMESSAGEFROMQQREQTYPE:      // 手Q -> 第三方应用，请求第三方应用向手Q发送消息
        {
            id<UIApplicationDelegate> appDelegate = [[UIApplication sharedApplication] delegate];
            if ([appDelegate isKindOfClass:sdkDemoAppDelegate.class]) {
                ((sdkDemoAppDelegate*)appDelegate).isRequestFromQQ = YES;
            }
            break;
        }
        case ESHOWMESSAGEFROMQQREQTYPE:
            if ([req isKindOfClass:ShowMessageFromQQReq.class]) {
                [self checkIfIsMALaunchApp:((ShowMessageFromQQReq*)req).message];
            }
            break;
        default:
        {
            break;
        }
    }
}

+ (void)onResp:(QQBaseResp *)resp
{
    switch (resp.type)
    {
        case ESENDMESSAGETOQQRESPTYPE:
        {
            SendMessageToQQResp* sendReq = (SendMessageToQQResp*)resp;
            NSString *message = sendReq.errorDescription;
            NSString *guildID = sendReq.otherInfo[@"guildID"];
            if ([sendReq.result isEqualToString:@"0"] && guildID && guildID.length > 0) {
                message = @"频道-操作成功";
            }
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:sendReq.result message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            break;
        }
        default:
        {
            break;
        }
    }
}
#endif
+ (void)handleSendResult:(QQApiSendResultCode)sendResult
{
    switch (sendResult)
    {
        case EQQAPISENDSUCESS:
            break;
        default: {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:nil message:[self showAlert:sendResult] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [msgbox show];
            break;
        }
    }
}

+ (NSString *)showAlert:(QQApiSendResultCode)sendResult {
    NSDictionary *messageDict = @{
        @(EQQAPISENDSUCESS): @"",
        @(EQQAPIAPPNOTREGISTED): @"App未注册",
        @(EQQAPIMESSAGECONTENTINVALID): @"发送参数错误",
        @(EQQAPIMESSAGECONTENTNULL): @"发送参数错误",
        @(EQQAPIMESSAGETYPEINVALID): @"发送参数错误",
        @(EQQAPIQQNOTINSTALLED): @"未安装手Q",
        @(EQQAPIQQNOTSUPPORTAPI): @"手Q API接口不支持",
        @(EQQAPIQZONENOTSUPPORTTEXT): @"空间分享不支持QQApiTextObject，请使用QQApiImageArrayForQZoneObject分享",
        @(EQQAPIQZONENOTSUPPORTIMAGE): @"空间分享不支持QQApiImageObject，请使用QQApiImageArrayForQZoneObject分享",
        @(EQQAPIVERSIONNEEDUPDATE): @"当前QQ版本太低，需要更新",
        @(ETIMAPIVERSIONNEEDUPDATE): @"当前TIM版本太低，需要更新",
        @(EQQAPITIMNOTINSTALLED): @"未安装TIM",
        @(EQQAPITIMNOTSUPPORTAPI): @"TIM API接口不支持",
        @(EQQAPISHAREDESTUNKNOWN): @"未指定分享到QQ或TIM",
        @(EQQAPIMESSAGE_MINI_CONTENTNULL): @"小程序必填参数为空",
        @(EQQAPI_INCOMING_PARAM_ERROR): @"外部传参错误",
        @(EQQAPI_THIRD_APP_GROUP_ERROR_APP_NOT_AUTHORIZIED): @"App未获得授权",
        @(EQQAPI_THIRD_APP_GROUP_ERROR_CGI_FAILED): @"CGI请求失败",
        @(EQQAPI_THIRD_APP_GROUP_ERROR_HAS_BINDED): @"该组织已经绑定群聊",
        @(EQQAPI_THIRD_APP_GROUP_ERROR_NOT_BINDED): @"该组织尚未绑定群聊",
        @(EQQAPI_THIRD_APP_GROUP_ERROR_HAS_UNBINDED): @"该组织已经解绑群聊",
        @(EQQAPI_IMAGE_SIZE_OUT_OF_BOUNND): @"图片或者缩略图尺寸超过限制，图片不能超过5M，缩略图不能超过1M",
        @(EQQAPI_TITLE_LENGTH_OUT_OF_BOUNND): @"标题长度超过限制（不能超过128）",
        @(EQQAPI_TITLE_NIL_ERROR): @"标题不能为空",
        @(EQQAPI_DESC_LENGTH_OUT_OF_BOUNND): @"描述信息长度超过限制（不能超过512）",
        @(EQQAPI_URL_LENGTH_OUT_OF_BOUNND): @"URL参数长度超过限制（不能超过1024）",
        @(EQQAPI_URL_NIL_ERROR): @"URL参数不能为空",
    };
    
    NSString *message = [NSString stringWithFormat:@"Error Code:%ld，具体原因见打印", (long)sendResult];
    if ([[messageDict allKeys] containsObject:@(sendResult)]) {
        message = messageDict[@(sendResult)];
    }
    return message;
}

// 如果是maLaunchApp的话，则alert一下看看参数是啥子
+ (void)checkIfIsMALaunchApp:(QQApiObject *)obj {
    if (![obj isKindOfClass:QQApiMiniProgramLaunchObject.class]) {
        return;
    }
    QQApiMiniProgramLaunchObject* maLaunchApp = (QQApiMiniProgramLaunchObject*)obj;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"小程序唤起互联demo" message:maLaunchApp.appParameter preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:actionCancel];
    
    id<UIApplicationDelegate> appDelegate = [[UIApplication sharedApplication] delegate];
    if ([appDelegate isKindOfClass:sdkDemoAppDelegate.class]) {
        UIViewController* vc = ((sdkDemoAppDelegate*)appDelegate).viewController;
        [vc presentViewController:alert animated:YES completion:nil];
    }
    
}
@end


@interface QQAPIDemoCommonController : QuickDialogController

@property (nonatomic, strong) NSString *binding_title;
@property (nonatomic, strong) NSString *binding_text;
@property (nonatomic, strong) NSString *binding_description;
@property (nonatomic, strong) NSString *binding_url;
@property (nonatomic, strong) UIImage *binding_previewImage;
@property (nonatomic, strong) NSString *binding_previewImageUrl;
@property (nonatomic, strong) NSString *binding_webpImageUrl;
@property (nonatomic, strong) NSString *binding_streamUrl;
@property (nonatomic, strong) NSString *binding_openID;
@property (nonatomic, strong) NSString *binding_subID;
@property (nonatomic, strong) NSString *binding_remark;

@property (nonatomic, strong) NSString *binding_ownerSignature;
@property (nonatomic, strong) NSString *binding_GameSectionID;
@property (nonatomic, strong) NSString *binding_GroupID;
@property (nonatomic, strong) NSString *binding_GroupKey;
@property (nonatomic, strong) NSString *binding_imageCount;
@property (nonatomic, strong) NSString *binding_bid;
@property (nonatomic, strong) NSString *binding_groupTribeName;

@property (nonatomic, strong) NSString *binding_appkey;

@property (nonatomic, strong) NSString *tenpayID;
@property (nonatomic, strong) NSString *tenpayAppInfo;
@property (nonatomic, strong) UIControl *qrcodePanel;
@property (nonatomic, strong) UIImageView *qrcodeImgView;

@property (nonatomic, strong) NSArray *imageAssetsForQZone;
@property (nonatomic, strong) NSURL *videoAssetForQZone;

// WPA
@property (nonatomic, strong) NSString *binding_uin;

@property (nonatomic, strong) QQApiObject *qqApiObject;
@property (nonatomic, strong) ArkObject *arkObject;

@property (nonatomic, assign) BOOL webpFlag;

- (void)doOpenApiExtraService:(NSDictionary *)userInfo;

@end

@implementation QQAPIDemoCommonController

- (id)init
{
    if (self = [super init])
    {
        self.webpFlag = NO;
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    if ([self.root.object isKindOfClass:[NSDictionary class]])
    {
        NSString *jsonConfig = self.root.object[@"jsonConfig"];
        if ([jsonConfig isKindOfClass:[NSString class]])
        {
            self.root = [QRootElement rootForJSON:jsonConfig withObject:nil];
        }
    }
    
    CGRect frame = [[self view] bounds];
    self.qrcodePanel = [[UIControl alloc] initWithFrame:frame];
    self.qrcodePanel.hidden = YES;
    self.qrcodePanel.backgroundColor = [UIColor colorWithWhite:0.9 alpha:0.9];
    [self.qrcodePanel addTarget:self action:@selector(onQRCodePanelClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.qrcodePanel];
    
    CGRect panelFrame = [self.qrcodePanel bounds];
    CGFloat minSize = MIN(panelFrame.size.width, panelFrame.size.height) * 0.9f;
    self.qrcodeImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, minSize, minSize)];
    self.qrcodeImgView.center = CGPointMake(CGRectGetMidX(panelFrame), CGRectGetMidY(panelFrame));
    [self.qrcodePanel addSubview:self.qrcodeImgView];
    
    if ([[self.root key] isEqualToString:@"QQAPIDemo"])
    {
        [[self currentNavContext] removeAllObjects];
    }
}

- (NSMutableDictionary *)currentNavContext
{
    UINavigationController *navCtrl = [self navigationController];
    NSMutableDictionary *context = objc_getAssociatedObject(navCtrl, (__bridge void *)(@"currentNavContext"));
    if (nil == context)
    {
        context = [NSMutableDictionary dictionaryWithCapacity:3];
        objc_setAssociatedObject(navCtrl, (__bridge void *)(@"currentNavContext"), context, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    return context;
}

- (void)onSwitchCFlag:(QElement *)sender
{
    if ([sender isKindOfClass:[QBooleanElement class]])
    {
        QBooleanElement *boolElem = (QBooleanElement *)sender;
        NSString *flagKey = boolElem.key;
        uint32_t flagValue = [boolElem.object[@"flagValue"] unsignedIntValue] * (!![boolElem boolValue]);
        [[self currentNavContext] setObject:[NSNumber numberWithUnsignedInt:flagValue] forKey:flagKey];

        NSLog(@"%@",[self currentNavContext]);
    }
}

- (uint64_t)shareControlFlags
{
    NSDictionary *context = [self currentNavContext];
    __block uint64_t cflag = 0;
    [context enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        if ([obj isKindOfClass:[NSNumber class]] &&
            [key isKindOfClass:[NSString class]] &&
            [key hasPrefix:@"kQQAPICtrlFlag"])
        {
            cflag |= [obj unsignedIntValue];
        }
    }];
    
    return cflag;
}

- (ShareDestType)getShareType
{
    BOOL flag = [[[NSUserDefaults standardUserDefaults] objectForKey:@"sdkSwitchFlag"] boolValue];
    return flag? ShareDestTypeTIM :ShareDestTypeQQ;
}

#if BUILD_QQAPIDEMO
- (void)onShowShareSubMenu:(QElement *)sender
{
    NSArray<NSString*>* entryList = @[@"inputArkJson", @"inputMiniAppid", @"inputMiniPath", @"inputMiniWebUrl", @"inputMiniType"];
    
    for (NSString* key in entryList) {
        QEntryElement *entry  = (QEntryElement *) [self.root elementWithKey:key];
        if(entry.key && entry.textValue){
            [[self currentNavContext] setObject:entry.textValue forKey:entry.key];
        }
    }
}

- (void)onShareText:(QElement *)sender
{
    [self.view endEditing:YES];
    [self.root fetchValueUsingBindingsIntoObject:self];
    
    QQApiTextObject *textObject = [QQApiTextObject objectWithText:self.binding_text ? : @""];
    [textObject setCflag:[self shareControlFlags]];
    if (textObject.cflag & kQQAPICtrlFlagQZoneShareOnStart) {
        UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"提示" message:@"纯文本暂不支持直接分享到Qzone" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
        [msgbox show];
        return;
    }
    
    _qqApiObject = textObject;
    QQApiSendResultCode ret = EQQAPISENDFAILD;
    QQBaseReq *req = [self getReq:textObject thisTypeEnableArk:YES arkJson:nil];
    ret = [QQApiInterface sendReq:req];
    [self handleSendResult:ret];
}

- (void)onShareWeiXin:(QElement *)sender {
    NSString *urlString = @"mqqapi://share/to_fri?file_type=news&src_type=app&version=1&callback_type=scheme&generalpastboard=1&shareType=0&callback_name=QQ41C152CF&objectlocation=pasteboard&cflag=0&previewimageUrl=aHR0cHM6Ly9tbWJpei5xcGljLmNuL3N6X21tYml6X2pwZy9iZWp5Ym1qNXNkempDYzQwZng0MGxBQXh4SGFQcnFycE5rN3JmdWljaWJ5OThPTDJGcVF0VmZCM0FSNlhJUGFESW81N3dqaWFCYlFBZWliU3pvcjlxMTNaWVEvMzAwP3d4X2ZtdD1qcGVnJnd4ZnJvbT03&title=aU9TIDE45p2l5LqG77yM5LuK5pma5YeM5pmoMeeCueinge+8gQ==&description=IA==&url=aHR0cDovL21wLndlaXhpbi5xcS5jb20vcz9fX2Jpej1NekF4TURNNU1qazJNdz09Jm1pZD0yNjUxOTMwNTAyJmlkeD0xJnNuPTZkZDcxYmYzYmEwZmE0MDZhM2FkYzAyZTE0YTM3MjliJmNoa3NtPTgwYjQ5YjZhYjdjMzEyN2MxOWUyMWNjNDYxYjJlNjM4NGVhYzJmOWFlYzMzMjkyNTcwOTY0M2M3ZDE1MmFjMjNkMTM3ODE3NWY0OWUmbXBzaGFyZT0xJnNjZW5lPTIzJnNyY2lkPTA2MTMxa2locFpnUjdPWE4ySXVXc3ZPdSZzaGFyZXJfc2hhcmVpbmZvPThlZTJjYjE3MWI3MjFkY2E1Y2I4YWEwODI2OGEwY2JhJnNoYXJlcl9zaGFyZWluZm9fZmlyc3Q9OGVlMmNiMTcxYjcyMWRjYTVjYjhhYTA4MjY4YTBjYmEjcmQ=&thirdAppDisplayName=5b6u5L+h";
    NSURL *url = [NSURL URLWithString:urlString];
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
    } else {
        [[UIApplication sharedApplication] openURL:url];
    }
}

- (void)onloadImage:(QElement *)sender
{
    [self.root fetchValueUsingBindingsIntoObject:self];
}


- (void)onShareImage:(QElement *)sender
{
    [self.view endEditing:YES];
    [self.root fetchValueUsingBindingsIntoObject:self];
    
    NSData *imgData = nil;
    NSData *preImgData = imgData;
    
    if (self.binding_previewImage)
    {
        NSData *selectedImgData = UIImageJPEGRepresentation(self.binding_previewImage, 1);
        NSData *selectedPreImgData = UIImageJPEGRepresentation(self.binding_previewImage, 0.20);//对于大于1M的图直接作为缩略图会过大，因此压缩系数要更小
        if (selectedImgData)
        {
            imgData = selectedImgData;
        }
        if (selectedPreImgData)
        {
            preImgData = selectedPreImgData;
        }
    } else {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *path = [documentsDirectory stringByAppendingString:SDK_TEST_IMAGE_FILE_NAME];
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]){
            imgData = [NSData dataWithContentsOfFile:path];
        }else {
            NSString *imgPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"test.gif"];
            imgData = [NSData dataWithContentsOfFile:imgPath];
        }
    }
    
#if !QQ_OPEN_SDK_LITE
    //游戏侧用这个接口
    QQApiImageObject *imgObj = [QQApiImageObject objectWithData:imgData
                                 previewImageData:preImgData
                                            title:self.binding_title ? : @"demo默认图片标题"
                                      description:self.binding_description ? : @"demo默认图片描述"
                                      tagName:@"testName" messageExt:@"testMessage"];
#else
    QQApiImageObject *imgObj = [QQApiImageObject objectWithData:imgData
                                 previewImageData:preImgData
                                            title:self.binding_title ? : @"demo默认图片标题"
                                      description:self.binding_description ? : @"demo默认图片描述"];
#endif
    
    
    
    
    [imgObj setCflag:[self shareControlFlags]];
    QQApiSendResultCode ret = [QQApiInterface sendReq:[self getReq:imgObj thisTypeEnableArk:YES arkJson:nil]];
    [self handleSendResult:ret];
}

- (QQBaseReq *)getReq:(QQApiObject *)qqobj thisTypeEnableArk:(BOOL)thisTypeEnableArk arkJson:(NSString *)arkJson
{
    SendMessageToQQReq *req = nil;
    if( thisTypeEnableArk && ((qqobj.cflag & kQQAPICtrlFlagQQShareEnableArk) == kQQAPICtrlFlagQQShareEnableArk) ){
        NSString *json = ( (arkJson == nil) ? [self getDebugArkJson] : arkJson);
        ArkObject *arkObj = [ArkObject objectWithData:json qqApiObject:qqobj];
        _arkObject = arkObj;
        req = [SendMessageToQQReq reqWithArkContent:arkObj];
    }
    else if ((qqobj.cflag & kQQAPICtrlFlagQQShareEnableMiniProgram) == kQQAPICtrlFlagQQShareEnableMiniProgram) {
            QQApiMiniProgramObject *miniObj = [QQApiMiniProgramObject new];
            miniObj.qqApiObject = qqobj;
        NSDictionary *context = [self currentNavContext];
        __block NSString *inputMiniAppid = nil;
        __block NSString *inputMiniPath = nil;
        __block NSString *inputMiniWebUrl = nil;
        __block NSString *inputMiniType = nil;
        [context enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            if ([obj isKindOfClass:[NSString class]] &&
                [key isKindOfClass:[NSString class]]) {
                if ([key isEqualToString:@"inputMiniAppid"]) {
                    inputMiniAppid = (NSString*)obj;
                } else if ([key isEqualToString:@"inputMiniPath"]) {
                    inputMiniPath = (NSString*)obj;
                } else if ([key isEqualToString:@"inputMiniWebUrl"]) {
                    inputMiniWebUrl = (NSString*)obj;
                } else if ([key isEqualToString:@"inputMiniType"]) {
                    inputMiniType = (NSString*)obj;
                }
            }
        }];
            miniObj.miniAppID = inputMiniAppid;
            miniObj.miniPath = inputMiniPath;
            miniObj.webpageUrl = inputMiniWebUrl;
            miniObj.miniprogramType = [inputMiniType integerValue];
            
            req = [SendMessageToQQReq reqWithMiniContent:miniObj];
    }
    else {
        _qqApiObject = qqobj;
        req = [SendMessageToQQReq reqWithContent:qqobj];
    }
    return req;
}

- (NSString *)getDebugArkJson
{
    
    NSDictionary *context = [self currentNavContext];
    __block NSString *arkJson = nil;
    [context enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        if ([obj isKindOfClass:[NSString class]] &&
            [key isKindOfClass:[NSString class]] &&
            [key isEqualToString:@"inputArkJson"])
        {
            arkJson = (NSString*)obj;
        }
    }];
    if (arkJson.length > 0) {
        return arkJson;
    }
    
    // 这已经失效了
//    NSData *objectData = [ @"{\"app\":\"com.tencent.eventshare.lua\",\"config\":{\"autosize\":true,\"ctime\":1574912215,\"forward\":true,\"token\":\"b8126b8e803b1c66f4afb639adf83933\",\"type\":\"normal\"},\"desc\":\"新闻\",\"meta\":{\"news\":{\"action\":\"\",\"android_pkg_name\":\"\",\"app_type\":1,\"appid\":102060558,\"desc\":\"定向分享描述\",\"jumpUrl\":\"www.qq.com\",\"preview\":\"http://url.cn/5RDvYnS\",\"source_icon\":\"\",\"source_url\":\"\",\"tag\":\"联调测试应用\",\"title\":\"定向分享标题\"}},\"prompt\":\"[分享]定向分享标题\",\"ver\":\"0.0.0.1\",\"view\":\"news\"}" dataUsingEncoding:NSUTF8StringEncoding];
    
    // 这才是ark的消息
    NSData *objectData = [ @"{\"app\":\"com.tencent.gamecenter.qqsy\",\"bizsrc\":\"\",\"config\":{\"ctime\":1692072340,\"forward\":1,\"token\":\"44948e7e5211f04c80e3cc1c710bc116\",\"type\":\"normal\"},\"desc\":\"\",\"extra\":{\"app_type\":1,\"appid\":1110196838,\"uin\":1550746206},\"meta\":{\"shareData\":{\"appid\":\"1110196838\",\"extData\":\"\",\"openId\":\"\",\"scene\":\"1027\",\"url\":\"\"}},\"prompt\":\"[应用]\",\"ver\":\"0.0.0.1\",\"view\":\"picView2\"}" dataUsingEncoding:NSUTF8StringEncoding];
    
    // 这是小程序的样式，不能用
//    NSData *objectData = [@"{\"app\":\"com.tencent.miniapp\",\"config\":{\"autoSize\":0,\"ctime\":1574826649,\"forward\":1,\"height\":272,\"token\":\"18608730ce9e9aca273ae30a6eb991ca\",\"type\":\"normal\",\"width\":253},\"desc\":\"form\",\"meta\":{\"detail\":{\"action\":\"\",\"app_type\":1,\"appid\":\"1108003473\",\"desc\":\"测试小程序消息\",\"icon\":\"https://qzonestyle.gtimg.cn/aoi/sola/20190603101743_oRx2w5EX9s.png\",\"jumpUrl\":\"https://docs.qq.com/doc/BqI21X2yZIht1Wa5TS2EGjbB05QQLU3t4SFA0D4QyU1D8UAQ0IQmKC2Cjyb92Epx2w1QB96n17FEoB312GIY0\",\"preview\":\"https://qqadapt.qpic.cn/txdocpic/0/2ed87844392eb0e84f8aa43e042341f2/0\",\"qqdocurl\":\"https://docs.qq.com/doc/BqI21X2yZIht1Wa5TS2EGjbB05QQLU3t4SFA0D4QyU1D8UAQ0IQmKC2Cjyb92Epx2w1QB96n17FEoB312GIY0\",\"tag\":\"debug\",\"title\":\"腾讯文档\",\"url\":\"https://docs.qq.com/doc/BqI21X2yZIht1Wa5TS2EGjbB05QQLU3t4SFA0D4QyU1D8UAQ0IQmKC2Cjyb92Epx2w1QB96n17FEoB312GIY0\"}},\"prompt\":\"[QQ小程序]收集表\",\"ver\":\"0.0.0.1\",\"view\":\"detail\"}" dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:objectData
                                                             options:NSJSONReadingMutableContainers // Pass 0 if you don't care about the readability of the generated string
                                                               error:nil];
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];



    NSString *jsonString = @"";

    if (! jsonData)
    {
        NSLog(@"Got an error: %@", error);
    }else
    {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }

    jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];  //去除掉首尾的空白字符和换行字符

    [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];

    return jsonString;
}

////网络单图分享
//- (void)onShareWebImage:(QElement *)sender
//{
//    [self.view endEditing:YES];
//    [self.root fetchValueUsingBindingsIntoObject:self];
//
//    QQApiWebImageObject *webImageObj = [QQApiWebImageObject
//                                         objectWithPreviewImageURL:[NSURL URLWithString:self.binding_previewImageUrl ? : @""]
//                                         title:self.binding_title ? : @""
//                                         description:self.binding_description ? : @""];
//    [webImageObj setCflag:[self shareControlFlags]];
//    _qqApiObject = webImageObj;
//    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:webImageObj];
//    QQApiSendResultCode ret = [QQApiInterface sendReq:req];
//    [self handleSendResult:ret];
//}

- (void)onShareMutileImage:(QElement *)sender
{
    uint64_t flag = [self shareControlFlags];
    if ((flag & kQQAPICtrlFlagQQShareFavorites) != kQQAPICtrlFlagQQShareFavorites) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"error" message:@"请你回到上一级目录，在顶头只打开'收藏'开关，再来测试。" delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil];
        [alertView show];
        return;
    }
    
    [self.view endEditing:YES];
    [self.root fetchValueUsingBindingsIntoObject:self];
    
    NSString *imgPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"test.gif"];
    NSData *imgData = [NSData dataWithContentsOfFile:imgPath];
    NSData *preImgData = imgData;
    if (self.binding_previewImage)
    {
        NSData *selectedImgData = UIImageJPEGRepresentation(self.binding_previewImage, 0.85);
        NSData *selectedPreImgData = UIImageJPEGRepresentation(self.binding_previewImage, 0.20);
        if (selectedImgData)
        {
            imgData = selectedImgData;
        }
        if (selectedPreImgData)
        {
            preImgData = selectedPreImgData;
        }
    }
    
    NSString *imgPath2 = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"news.jpg"];
    NSData *imgData2 = [NSData dataWithContentsOfFile:imgPath2];
    NSString *imgPath3 = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"img.jpg"];
    NSData *imgData3 = [NSData dataWithContentsOfFile:imgPath3];
    
    NSArray* imgArray = [NSArray arrayWithObjects:imgData, imgData2, imgData3, nil]; //多个图片
    QQApiImageObject *imgObj =  [QQApiImageObject objectWithData:imgData
                     previewImageData:preImgData
                                title:self.binding_title ? : @""
                          description:self.binding_description ? : @""
                       imageDataArray:imgArray];
    
    //key_ImageDataArray;
    
    [imgObj setCflag:[self shareControlFlags]];
    _qqApiObject = imgObj;
    QQApiSendResultCode ret = [QQApiInterface sendReq:[self getReq:imgObj thisTypeEnableArk:YES arkJson:nil]];
    [self handleSendResult:ret];
}

- (void)onShareNewsLocal:(QElement *)sender
{
    [self.view endEditing:YES];
    [self.root fetchValueUsingBindingsIntoObject:self];
    
    NSString *previewPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"news.jpg"];
    NSData *previewData = [NSData dataWithContentsOfFile:previewPath];
    if (self.binding_previewImage)
    {
        NSData *selectedImgData = UIImageJPEGRepresentation(self.binding_previewImage, 0.20);
        if (selectedImgData)
        {
            previewData = selectedImgData;
        }
    }
    
    NSString *utf8String = [self.binding_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    QQApiNewsObject *newsObj = [QQApiNewsObject objectWithURL:[NSURL URLWithString:utf8String ? : @""]
                                                        title:self.binding_title ? : @""
                                                  description:self.binding_description ? : @""
                                             previewImageData:previewData];
    [newsObj setCflag:[self shareControlFlags]];
    _qqApiObject = newsObj;
    QQApiSendResultCode ret = [QQApiInterface sendReq:[self getReq:newsObj thisTypeEnableArk:YES arkJson:nil]];
    [self handleSendResult:ret];
}

- (void)onShareNewsWeb:(QElement *)sender
{
    [self.view endEditing:YES];
    [self.root fetchValueUsingBindingsIntoObject:self];
    
    NSString *utf8String = [self.binding_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    QQApiNewsObject *newsObj = nil;
    if (self.webpFlag) {
        newsObj = [QQApiNewsObject objectWithURL:[NSURL URLWithString:utf8String ? : @""]
                                                            title:self.binding_title ? : @""
                                                      description:self.binding_description ? : @""
                                                  previewImageURL:[NSURL URLWithString:self.binding_webpImageUrl ? : @""]];
    }
    else {
        newsObj = [QQApiNewsObject objectWithURL:[NSURL URLWithString:utf8String ? : @""]
                                               title:self.binding_title ? : @""
                                         description:self.binding_description ? : @""
                                     previewImageURL:[NSURL URLWithString:self.binding_previewImageUrl ? : @""]];
    }
    [newsObj setCflag:[self shareControlFlags]];
    _qqApiObject = newsObj;
    QQApiSendResultCode ret = [QQApiInterface sendReq:[self getReq:newsObj thisTypeEnableArk:YES arkJson:nil]];
    [self handleSendResult:ret];
}

- (void)onSwitchWebpFlag:(QElement *)sender {
    QBooleanElement *boolElem = (QBooleanElement *)sender;
    uint32_t flagValue = [boolElem.object[@"flagValue"] unsignedIntValue] * (!![boolElem boolValue]);
    self.webpFlag = flagValue > 0 ? YES : NO;
}

- (void)onShareAudio:(QElement *)sender
{
    [self.view endEditing:YES];
    [self.root fetchValueUsingBindingsIntoObject:self];
    
    if (self.binding_streamUrl == nil || [self.binding_streamUrl length] == 0) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"error" message:@"请输入streamUrl" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
        alertView.tag = 0x110;
        [alertView show];
        
        return;
    }
    
    NSData *previewData = nil;
    
    NSString *utf8String = [self.binding_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
    QQApiAudioObject* audioObj = [QQApiAudioObject objectWithURL:[NSURL URLWithString:utf8String ? : @""] title:self.binding_title ? : @"" description:self.binding_description ? : @"" previewImageData:previewData];
    
    utf8String = [self.binding_previewImageUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [audioObj setPreviewImageURL:[NSURL URLWithString: utf8String? : @""]];
    utf8String = [self.binding_streamUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [audioObj setFlashURL:[NSURL URLWithString:utf8String ? : @""]];
    [audioObj setCflag:[self shareControlFlags]];
    _qqApiObject = audioObj;
    QQApiSendResultCode ret = [QQApiInterface sendReq:[self getReq:audioObj thisTypeEnableArk:YES arkJson:nil]];
    [self handleSendResult:ret];
}

-(void)onShareLocalFile:(QElement*)sender
{
    [self.view endEditing:YES];
    [self.root fetchValueUsingBindingsIntoObject:self];
    
//    NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"test.txt"];
    NSString *filePath = [QQApiInterface getLogFilePath];
    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    
    QQApiFileObject *fileObj = [QQApiFileObject objectWithData:fileData
                                               previewImageData:nil
                                                          title:self.binding_title ? : @""
                                                    description:self.binding_description ? : @""];
    
    if (self.binding_description != nil && ![self.binding_description isEqualToString:@""])
    {
        fileObj.fileName = self.binding_description;
    } else {
        fileObj.fileName = @"test.txt";
    }
    [fileObj setCflag:0x10];
    _qqApiObject = fileObj;
    QQApiSendResultCode ret = [QQApiInterface sendReq:[self getReq:fileObj thisTypeEnableArk:YES arkJson:nil]];
    [self handleSendResult:ret];

}

- (void)onShareVideo:(QElement *)sender
{
    [self.view endEditing:YES];
    [self.root fetchValueUsingBindingsIntoObject:self];

    NSString *previewPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"video.jpg"];
    NSData* previewData = [NSData dataWithContentsOfFile:previewPath];
    if (self.binding_previewImage)
    {
        NSData *selectedImgData = UIImageJPEGRepresentation(self.binding_previewImage, 0.20);
        if (selectedImgData)
        {
            previewData = selectedImgData;
        }
    }
    
    NSString *utf8String = [self.binding_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    QQApiVideoObject *videoObj = [QQApiVideoObject objectWithURL:[NSURL URLWithString:utf8String ? : @""]
                                                           title:self.binding_title ? : @""
                                                     description:self.binding_description ? : @""
                                                previewImageData:previewData];
    
    
    utf8String = [self.binding_streamUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [videoObj setFlashURL:[NSURL URLWithString:utf8String ? : @""]];
    [videoObj setCflag:[self shareControlFlags]];
    _qqApiObject = videoObj;
    QQApiSendResultCode ret = [QQApiInterface sendReq:[self getReq:videoObj thisTypeEnableArk:YES arkJson:nil]];
    [self handleSendResult:ret];
}
#if OPEN_API_ADD_FRIEND
- (void)onAddOpenFriend:(QElement *)sender {
    [self.view endEditing:YES];
    [self.root fetchValueUsingBindingsIntoObject:self];
    
    QQApiAddFriendObject *object = [[QQApiAddFriendObject alloc] initWithOpenID:self.binding_openID];
    object.description = self.binding_description;
    object.subID = self.binding_subID;
    object.remark = self.binding_remark;
    object.shareDestType = [self getShareType];
    SendMessageToQQReq* req = [SendMessageToQQReq reqWithContent:object];
    QQApiSendResultCode sent = [QQApiInterface sendReq:req];
    [self handleSendResult:sent];
}
#endif
#if OPEN_API_UNBIND_GROUP
#pragma mark 第三方app新的解绑群
- (void)thirdAppUnbindGroup:(QElement *)sender
{
    [self.view endEditing:YES];
    [self.root fetchValueUsingBindingsIntoObject:self];
    
    if ([[TencentOAuth sharedInstance].openId length] == 0)
    {
        UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"需要先登录" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
        [msgbox show];
        return;
    }
    
      NSString* appId = [TencentOAuth sharedInstance].appId;
    QQApiThirdAppUnBindGroupObject *object = [[QQApiThirdAppUnBindGroupObject alloc] initWithAccessToken:[TencentOAuth sharedInstance].accessToken
                      payToken:[TencentOAuth sharedInstance].passData[@"pay_token"]
                         pfkey:[TencentOAuth sharedInstance].passData[@"pfkey"]
                       unionID:self.binding_GroupID
                        openId:[TencentOAuth sharedInstance].openId
                         appId:appId];
    object.shareDestType = [self getShareType];
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:object];
    
    [QQApiInterface sendThirdAppUnBindGroupReq:req resultBlock:^(NSDictionary *result) {
        NSLog(@"%s, %@", __func__, result);
        QQApiSendResultCode resultCode = [result[@"QQApiSendResultCode"] integerValue];
        [self handleSendResult:resultCode];
//        //4.解析服务器返回的数据
//        NSString *str = result[@"QQApiSendResultMsg"];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [[[UIAlertView alloc] initWithTitle:nil message:str delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
//        });
    }];
}
#endif //#if OPEN_API_UNBIND_GROUP
- (NSDictionary *)jasonValueWithStringData:(NSData *)data
{
    if (nil == data)
    {
        return nil;
    }

    NSError * error = nil;
    id jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
    if (!jsonDict)
    {
        NSLog(@"JSONValue errcode = %ld, msg = %@", (long)error.code, error.description);
    }
    return jsonDict;
}

- (NSString*)serializeURL:(NSString *)baseUrl
                   params:(NSDictionary *)params {
    
    NSURL* parsedURL = [NSURL URLWithString:baseUrl];
    NSString* queryPrefix = parsedURL.query ? @"&" : @"?";
    
    NSMutableArray* pairs = [NSMutableArray array];
    for (NSString* key in [params keyEnumerator]) {
        NSString* escaped_value = (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(
                                                                                      NULL, /* allocator */
                                                                                      (CFStringRef)[params objectForKey:key],
                                                                                      NULL, /* charactersToLeaveUnescaped */
                                                                                      (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                                      kCFStringEncodingUTF8);
        
        [pairs addObject:[NSString stringWithFormat:@"%@=%@", key, escaped_value]];
    }
    NSString* query = [pairs componentsJoinedByString:@"&"];
    
    return [NSString stringWithFormat:@"%@%@%@", baseUrl, queryPrefix, query];
}

#if OPNE_API_BIND_GROUP
#pragma mark 第三方app新的绑群
- (void)thirdAppBindGroup:(QElement *)sender
{
    [self.view endEditing:YES];
    [self.root fetchValueUsingBindingsIntoObject:self];
    
    if ([[TencentOAuth sharedInstance].openId length] == 0)
    {
        UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"需要先登录" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
        [msgbox show];
        return;
    }
    
    NSString *displayname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
    QQApiThirdAppBindGroupObject *object = [[QQApiThirdAppBindGroupObject alloc] initWithAccessToken:[TencentOAuth sharedInstance].accessToken payToken:[TencentOAuth sharedInstance].passData[@"pay_token"] pfkey:[TencentOAuth sharedInstance].passData[@"pfkey"] unionID:self.binding_GroupID appDisplayName:displayname];
    object.shareDestType = [self getShareType];
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:object];
    
    [QQApiInterface sendThirdAppBindGroupReq:req resultBlock:^(NSDictionary *result) {
        NSLog(@"%s, %@", __func__, result);
        QQApiSendResultCode resultCode = [result[@"QQApiSendResultCode"] integerValue];
        [self handleSendResult:resultCode];
    }];
}
#endif //#if OPNE_API_BIND_GROUP

#if OPNE_API_GAME_BIND_GROUP
//计算签名+绑定
// 绑群
- (void)onGenerateSignatureBind:(QElement *)sender
{
    [self.view endEditing:YES];
    [self.root fetchValueUsingBindingsIntoObject:self];

    if ([[TencentOAuth sharedInstance].openId length] == 0)
    {
        UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"需要先登录" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
        [msgbox show];
        return;
    }

    NSString * orgStr = [NSString stringWithFormat:@"%@_%@_%@_%@_%@",
                         [TencentOAuth sharedInstance].openId,
                         [TencentOAuth sharedInstance].appId,
                         self.binding_appkey,
                         self.binding_GroupID,
                         self.binding_GameSectionID];
    NSData * data = [orgStr dataUsingEncoding:NSUTF8StringEncoding];
    NSString * hexStr = [data md5];

    NSString * displayname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
    QQApiGameConsortiumBindingGroupObject *object = [[QQApiGameConsortiumBindingGroupObject alloc] initWithGameConsortium:hexStr
                                                                                                                  unionid:self.binding_GroupID
                                                                                                                   zoneID:self.binding_GameSectionID
                                                                                                           appDisplayName:displayname];
    object.shareDestType = [self getShareType];
    SendMessageToQQReq* req = [SendMessageToQQReq reqWithContent:object];
    QQApiSendResultCode sent = [QQApiInterface sendReq:req];
    [self handleSendResult:sent];

}
#endif //#if OPNE_API_GAME_BIND_GROUP

- (void)showErrorDialog:(NSString *)errorString {
    [[[UIAlertView alloc] initWithTitle:nil message:errorString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
}
#if OPNE_API_GAME_BIND_GROUP
//绑定
- (void)onGameConsortiumBindingGroup:(QElement *)sender
{
    [self.view endEditing:YES];
    [self.root fetchValueUsingBindingsIntoObject:self];
    
    if ([[TencentOAuth sharedInstance].openId length] == 0) {
        UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"需要先登录" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
        [msgbox show];
        return;
    }
    
    NSString * displayname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
    QQApiGameConsortiumBindingGroupObject *object = [[QQApiGameConsortiumBindingGroupObject alloc] initWithGameConsortium:self.binding_ownerSignature
                                                                                                                  unionid:self.binding_GroupID
                                                                                                                   zoneID:self.binding_GameSectionID
                                                                                                           appDisplayName:displayname];
    object.shareDestType = [self getShareType];
    SendMessageToQQReq* req = [SendMessageToQQReq reqWithContent:object];
    QQApiSendResultCode sent = [QQApiInterface sendReq:req];
    [self handleSendResult:sent];
}
#endif //#if OPNE_API_GAME_BIND_GROUP
#if OPEN_API_JOIN_GROUP
#pragma mark 第三方app新的加群
- (void)thirdAppJoinGroup:(QElement *)sender
{
    [self.view endEditing:YES];
    [self.root fetchValueUsingBindingsIntoObject:self];
    
    if ([[TencentOAuth sharedInstance].openId length] == 0)
    {
        UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"需要先登录" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
        [msgbox show];
        return;
    }
    
    QQApiThirdAppJoinGroupObject *object = [QQApiThirdAppJoinGroupObject objectWithAccessToken:[TencentOAuth sharedInstance].accessToken payToken:[TencentOAuth sharedInstance].passData[@"pay_token"] pfkey:[TencentOAuth sharedInstance].passData[@"pfkey"] unionID:self.binding_GroupID];
    object.shareDestType = [self getShareType];
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:object];
    // 校验是否已经绑群
    [QQApiInterface sendThirdAppJoinGroupReq:req resultBlock:^(NSDictionary *result) {
        NSLog(@"%s, %@", __func__, result);
        QQApiSendResultCode resultCode = [result[@"QQApiSendResultCode"] integerValue];
        [self handleSendResult:resultCode];
    }];
}
#endif // #ifndef OPEN_API_JOIN_GROUP

#if OPEN_API_JOIN_GROUP_OLD
// 加群
- (void)onJoinGroup:(QElement *)sender
{
    [self.view endEditing:YES];
    [self.root fetchValueUsingBindingsIntoObject:self];

    if (self.binding_GroupKey && [self.binding_GroupKey length] > 0)
    {
        //ret = [QQApi joinGroup:self.binding_GroupID key:self.binding_GroupKey];
        QQApiJoinGroupObject *object = [QQApiJoinGroupObject objectWithGroupInfo:self.binding_GroupID key:self.binding_GroupKey];
        object.shareDestType = [self getShareType];
        SendMessageToQQReq* req = [SendMessageToQQReq reqWithContent:object];
        QQApiSendResultCode sent = [QQApiInterface sendReq:req];
        [self handleSendResult:sent];

    }
}
#endif //#if OPEN_API_JOIN_GROUP_OLD

- (NSInteger)GetRandomNumber:(NSInteger)start to:(NSInteger)end
{
    return (NSInteger)(start + (arc4random() % (end - start + 1)));
}

- (void)handleSendResult:(QQApiSendResultCode)sendResult
{
    [QQApiShareEntry handleSendResult:sendResult];
}

#endif

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 0xAA)
    {
        SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:_qqApiObject];
        QQApiSendResultCode sent = 0;
        if (0 == buttonIndex)
        {
            sent = [QQApiInterface SendReqToQZone:req];
        }
        else if(1 == buttonIndex)
        {
            sent = [QQApiInterface sendReq:req];
        }
        [self handleSendResult:sent];
    }
}

/*
 * 目前已经支持的手Q扩展IM能力，即ServiceID值包括：
 * 18 - 打开聊天会话（手Q版本 >= 8.1.5）
 * 19 - 打开视频通话（手Q版本 >= 8.1.5）
 * 20 - 打开语音通话（手Q版本 >= 8.1.5）
 * 3002 - 同步状态到手Q 手Q版本 > 8.8.70
 * 从互联SDK 3.6.0版本开始使用QQApiCommonServiceObject替代QQApiExtraServiceObject发送通用扩展业务消息
 */
- (void)doOpenApiExtraService:(NSDictionary *)userInfo
{
//    if ([[TencentOAuth sharedInstance].openId length] == 0) {
//        UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"需要先登录" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
//        [msgbox show];
//        return;
//    }
    
    NSString *serviceId = userInfo[@"serviceId"];
    NSString *openId = userInfo[@"openId"];
    NSString *toUin = userInfo[@"toUin"];
    NSDictionary *extendInfo = userInfo[@"extendInfo"];
    BOOL isNewExtendService = [userInfo[@"isNewExtendService"] boolValue];
    if ([serviceId length] == 0) {
        UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"需填写有效ServiceID" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
        [msgbox show];
        return;
    }
    
    
    QQApiCommonServiceObject *commonServiceObject = [[QQApiCommonServiceObject alloc] initWithOpenID:openId
                                                                                           serviceID:serviceId
                                                                                          extendInfo:extendInfo];
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:commonServiceObject];
    
    if (!isNewExtendService) {
        QQApiExtraServiceObject *extraServiceObject = [[QQApiExtraServiceObject alloc] initWithOpenID:openId serviceID:serviceId];
        extraServiceObject.toUin = toUin;
        extraServiceObject.extraInfo = extendInfo;
        req = [SendMessageToQQReq reqWithContent:extraServiceObject];
    }
    
    QQApiSendResultCode sent = [QQApiInterface sendReq:req];
    [self handleSendResult:sent];
}

@end

#pragma mark - ExtraService
@implementation QQApiExtraServiceEntry
+ (void)StartCallApiExtraService:(NSDictionary *)userInfo
{
    QQAPIDemoCommonController *contr = [QQAPIDemoCommonController new];
    [contr doOpenApiExtraService:userInfo];
}

@end
